package org.budo.spring.beans.factory.xml.parser.async;

import org.budo.spring.beans.factory.xml.parser.BudoSpringBeanDefinitionParser;
import org.budo.support.lang.util.StringUtil;
import org.budo.support.spring.bean.factory.support.BeanBuilder;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;

import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 */
@Slf4j
public class AsyncServiceBeanDefinitionParser extends BudoSpringBeanDefinitionParser {
    private static final String BUDO_ASYNC_SERVICE_BEAN_TYPE = "org.budo.dubbo.protocol.async.config.BudoAsyncServiceBean";

    @Override
    public BeanDefinition parse(Element element, ParserContext parserContext) {
        String ref = element.getAttribute("ref");
        if (StringUtil.isNullOrEmpty(ref)) {
            throw new IllegalArgumentException("#38 ref required, element=" + element + ", parserContext=" + parserContext);
        }

        String id = element.getAttribute("id");
        if (StringUtils.isEmpty(id)) {
            id = "budo:async-service:" + element.getAttribute("ref");
        }

        String repositoryName = element.getAttribute("repository");
        if (StringUtil.isNullOrEmpty(repositoryName)) {
            repositoryName = this.repositoryName();
        }

        String interfaceType = element.getAttribute("interface");
        if (StringUtil.isNullOrEmpty(interfaceType)) {
            interfaceType = this.interfaceType(ref);
        }

        new BeanBuilder() //
                .id(id) //
                .type(BUDO_ASYNC_SERVICE_BEAN_TYPE) //
                .property("asyncRepositoryBeanName", repositoryName) //
                .property("interfaceType", interfaceType) //
                .ref("instance", ref) //
                .registerTo(parserContext.getRegistry()); //

        log.info("#25 beanName=" + id);
        return null;
    }

    private String interfaceType(String ref) {
        throw new RuntimeException();
    }

    private String repositoryName() {
        throw new RuntimeException();
    }
}